<?php
/**
 * Created by PhpStorm.
 * User: tiemeng
 * Date: 16/1/14
 * Time: 17:06
 */
include "group.php";
class groupWebController extends groupController{

    public $result=array();
    public function __construct()
    {
        header('Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, PATCH, DELETE');
        header('Access-Control-Allow-Headers:X-Requested-With,content-type');
        header('Access-Control-Allow-Credentials:true');
        header("Access-Control-Allow-Origin:*");
        parent::__construct('show');
        $this->in_user();
    }


    /**
     * 总排行
     */
    public function doranking(){
        $redisKey = REDIS_PREFIX."groupMileage";
        $gids = $this->redis->ZREVRANGE($redisKey,0,99);
        foreach($gids as $k=>$gid){
            $gInfo = $this->load('group')->getGroupInfo($gid);
            $status = $this->load('group')->getGroupStatus($this->uid, $gid);
            $rank[$k]['rank'] = $k+1;
            $rank[$k]['name'] = $gInfo['name'];
            $rank[$k]['gid'] = $gInfo['gid'];
            $rank[$k]['slogan'] = $gInfo['slogan'];
            $rank[$k]['joinNum'] = $gInfo['members'];
            $rank[$k]['header'] = $gInfo['header'];
            $rank[$k]['totalMileage'] = $this->load('group')->getTotalMileageByGid($gid);
            $rank[$k]['authenticate'] = $this->load('group')->isAuth($gid);
            $act = $this->load('groupActivity')->getIngAct($gid,0,1);
            $rank[$k]['isActivity'] =  empty($act) ? 0 : 1;
            $rank[$k]['status'] = $status;
        }
        $this->result =  compact('rank');
    }

    /**
     * 我的群组排行
     */
    public function domyGroupRank(){
        if(!$this->uid){
            $_ENV['error']->getErrors(201);
            exit;
        }
        $gid = common::request('gid','G','0');
        $direc = common::request('direc',"G");
        $offset = common::request('offset','G',20);
        $info = $this->load('group')->getMGrank($this->uid,$gid,$direc,$offset);
        $rank = array();
        $i = 0;
        foreach($info as $gid=>$totalMileage){
            $r = intval($this->redis->zrevrank(REDIS_PREFIX."groupMileage",$gid));
            $status = $this->load('group')->getGroupStatus($this->uid, $gid);
            $rank[$i]['rank'] =  $r >= 2000 ? "2000+" : ($r + 1);
            $gInfo = $this->load('group')->getGroupInfo($gid);
            $rank[$i]['name'] = $gInfo['name'];
            $rank[$i]['joinNum'] = $gInfo['members'];
            $rank[$i]['gid'] = $gid;
            $rank[$i]['header'] = $gInfo['header'];
            $rank[$i]['authenticate'] = $this->load('group')->isAuth($gid);
            $rank[$i]['totalMileage'] = $totalMileage;
            $act = $this->load('groupActivity')->getIngAct($gid,0,1);
            $rank[$i]['isActivity'] =  empty($act) ? 0 : 1;
            $rank[$i]['status'] =  $status;
            $i++;
        }
        $this->result = compact('rank');
    }

    /**
     * 我的活动
     */
    public function domyActivity(){
        if(!$this->uid){
            $_ENV['error']->getErrors(201);
            exit;
        }
        $aid = common::request('aid','G',0);
        $direc = common::request('direc',"G",'next');
        $offset = common::request('offset','G',20);
        $aids = $this->load('groupActivity')->getMyActivity($this->uid,$aid,$direc,$offset);
        $activity = array();
        foreach($aids as $id){
            $info = $this->load('groupActivity')->getActByAid($id);
            if(isset($info['aid'])){
                if($info['type'] > 2){
                    $gids = $this->redis->smembers(REDIS_PREFIX."ACTaccept_".$id);
                    foreach($gids as $gid){
                        if($this->load('group')->getGroupStatus($this->uid, $gid) == 0 && $this->redis->sismember(REDIS_PREFIX."GAJoin_".$gid."_".$id,$this->uid)){
                            $info['joinNum'] = $this->load('groupActivity')->joinNum($gid,$id);
                            $info['gid'] = $gid;
                            $info['type'] = intval($info['type']);
                            $info['name'] = $this->load('groupActivity')->getGiftName($info['aid']);
                            $activity[] = $info;
                        }
                    }
                }else{
                    $info['joinNum'] = $this->load('groupActivity')->joinNum($info['gid'],$info['aid']);
                    $info['type'] = intval($info['type']);
                    $activity[] = $info;
                }
            }

        }
        $activity = array_slice($activity,0,$offset);
        $this->result = compact('activity');
    }

    /**
     * 活动列表
     */
    public function doactivityList(){
        $uid = $this->uid;
        $aid = common::request('aid','G',0);
        $direc = common::request('direc',"G",'next');
        $offset = common::request('offset','G',20);
        $aids =  $this->load('groupActivity')->getActList(0,$aid,$direc,$offset);
        $activity = array();
        foreach($aids as $id){
            $info = $this->load('groupActivity')->getActByAid($id['aid']);
            $info['name'] = '';
            $info['header'] = '';
            if($info['gid'] > 0){
                $gInfo = $this->load('group')->getGroupInfo($info['gid']);
                $info['name'] = $gInfo['name'];
                $info['header'] = $gInfo['header'];
            }
            $info['isJoin'] = $this->load('groupActivity')->isJoin($info['aid'],$uid,$info['gid']);
            $info['joinNum'] = $this->load('groupActivity')->joinNum($info['gid'],$info['aid']);
            $info['cost'] = intval($info['cost']);
            $info['type'] = intval($info['type']);
            $info['groupStatus'] = $this->load('group')->getGroupStatus($uid,$info['gid']);
            $activity[] = $info;
        }
        $this->result = compact('activity');
    }

    /**
     * 活动统计
     */
    public function dostatistics(){
        $gid = common::request('gid','G');
        $aid = common::request('aid',"G");
        if(empty($gid) || empty($aid)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $uid = $this->uid == null ? '' : $this->uid;
        $curInfo = $this->load('client')->getUserInfo($uid);
        $uday = intval($this->redis->zscore(REDIS_PREFIX."GADay_{$gid}_{$aid}",$uid));
        $umileage = floatval($this->redis->hget(REDIS_PREFIX."UDPerDay_{$uid}_{$aid}_{$gid}",date("Ymd")));
        $utotalMileage = floatval($this->redis->zscore(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$uid));
        $actInfo = $this->load('groupActivity')->getActByAid($aid);
        if($actInfo['type'] == 2 || $actInfo['type'] == 4 ){
            $ids = $this->redis->zrevrange(REDIS_PREFIX."GADay_{$gid}_{$aid}",0,-1);
        }else{
            $ids = $this->redis->zrevrange(REDIS_PREFIX."GARecord_{$gid}_{$aid}",0,-1);
        }

        $target = $actInfo['target'];
        $num = 0;
        $fnum = 0;
        $members = array();
        foreach($ids as $k=>$id){
            $userInfo = $this->load('client')->getUserInfo($id);
            $info['uid'] = $id;
            $info['header'] = $userInfo['header'];
            $info['name'] = $userInfo['nickname'];
            $info['mileage'] = floatval($this->redis->hget(REDIS_PREFIX."UDPerDay_{$id}_{$aid}_{$gid}",date("Ymd")));
            $info['tMileage'] = floatval($this->redis->zscore(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$id));
            $info['day'] = intval($this->redis->zscore(REDIS_PREFIX."GADay_{$gid}_{$aid}",$id));
            if(($actInfo['type'] == 2 || $actInfo['type'] == 4) && $info['mileage'] >= $target){
               $num += 1;
            }
            if(($actInfo['type'] == 1 || $actInfo['type'] == 3) && $info['tMileage'] >= $target){
                $num += 1;
            }
            if($info['day'] >= $actInfo['days']){
                $fnum += 1;
            }
            $info['fRate'] = ($target > 0) ? ($info['tMileage'] / $target) : 0;//完成率
            $info['rank'] = $k + 1;
            $info['totalRate'] = $userInfo['total_rate'];
            $members[] = $info;
        }
        $data = array(
            'nickname' => $curInfo['nickname'],
            'header' => $curInfo['header'],
            'uid' => $uid,
            'uday'=>$uday,//用户累计打卡天数
            'umileage'=>$umileage,//当前用户今日里程
            'utMileage'=>$utotalMileage,//用户累计
            "type"=>$actInfo['type'],
            "fNum"=>$fnum, //累计达标人
            'num'=> $num, //今天达标人数
            'stime'=>$actInfo['stime'],
            'etime'=>$actInfo['etime'],
            'days'=>$actInfo['days'],
            'target'=>$target,
            'members'=>$members,
            "totalRate" => intval($this->redis->hlen(REDIS_PREFIX.'UDPerDay_'.$uid."_".$aid."_".$gid)),
            'isJoin' => $this->load('groupActivity')->isJoin($aid,$uid,$gid)
        );
        $this->result = $data;
    }

    /**
     * 群认证
     */
    public function doauthGroup(){
        $uid = $this->uid;
        $gid = common::request('gid',"P");
        $realname = common::request('name',"P");
        $phone = common::request('phone',"P");
        $card = common::request('card',"P");
        $info = common::request('info','P');
        $oid = common::request('oid','P');
        if(empty($gid) || empty($realname) || empty($phone) || empty($phone) || empty($card) || empty($info)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $img = $this->redis->get(REDIS_PREFIX."AuthImg_".$oid);
        $data = compact('uid','gid','realname','phone','card','info','img','add_time');
        $info = $this->load('group')->getAuthGroup($gid);
        if(!empty($info)){
            $data['id'] = $info['id'];
        }
        $this->db->updateRowTable('r_group_auth',$data);
        $this->redis->del(REDIS_PREFIX."AuthImg_".$oid);
        $this->result['is_success'] = 1;
    }

    /**
     * 认证详情
     */
    public function doauthDetail(){
        $gid = common::request("gid",'G');
        if(empty($gid)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $info = $this->load('group')->getAuthGroup($gid);
        $gInfo = $this->load('group')->getGroupInfo($gid);
        $info['header'] = $gInfo['header'];
        $info['name'] = $gInfo['name'];
        $info['img'] = !empty($info['img']) ? json_decode($info['img']) : '';
        $this->result = $info;

    }

    /**
     * 群组详情
     */
    public function dogroupDetail(){
        $gid = common::request("gid",'G');
        $info = $this->load('group')->getGroupInfo($gid);
        if(empty($info)){
            $_ENV['error']->getErrors(905);
            exit;
        }

        $this->result = $info;

    }

    /**
     * 群组活动列表
     */
    public function dogroupActivityList(){
        $aid = common::request('aid','G',0);
        $gid = common::request('gid','G');
        $direc = common::request('direc','G','next');
        $offset = common::request('offset','G',20);
        $uid = $this->uid;
        if(empty($gid)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $activity = array();
        $aids = $this->load('groupActivity')->getActList($gid,$aid,$direc,$offset);
        foreach($aids as $id){
            $info = $this->load('groupActivity')->getActByAid($id);
            if(isset($info['aid'])){
                $info['isJoin'] = $this->load('groupActivity')->isJoin($info['aid'],$uid,$gid);
                $info['joinNum'] = $this->load('groupActivity')->joinNum($gid,$info['aid']);
                $info['type'] = intval($info['type']);
                $info['gid'] = $gid;
                $info['name'] = $this->load('groupActivity')->getGiftName($info['aid']);
                $activity[] = $info;
            }
        }
        $this->result = compact('activity');
    }

    public function dodetail(){
        $aid = common::request('aid','G');
        $gid = common::request('gid','G',0);
        $uid = $this->uid;
        if(empty($aid)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        
        $info = $this->load('groupActivity')->getActByAid($aid);
        $groupInfo = $this->load('group')->getGroupInfo($gid);
        $joins = array();
        $nickName = '';
        $header = '';
        $role = $this->load('group')->getGroupRole($gid,$uid);
        //非官方活动
        if($info['type'] < 3){
            $userInfo = $this->load('client')->getUserInfo($info['uid']);
            $nickName = $userInfo['nickname'];
            $header = $userInfo['header'];
        }
        $join = array_slice($this->redis->smembers(REDIS_PREFIX."GAJoin_".$gid."_".$aid),0,8);
        foreach($join as $item){
            $id = is_array($item) ? $item['uid'] : $item;
            $user = $this->load('client')->getUserInfo($id);
            $uinfo['header'] = $user['header'];
            $uinfo['uid'] = $id;
            $joins[] = $uinfo;
        }
        $activity = $this->load('groupActivity')->getIngAct($gid,$aid,3);
        $actList = array();
        foreach($activity as $k=>$val){
            $actList[$k]['aid'] = $val['aid'];
            $actList[$k]['title'] = $val['title'];
            $actList[$k]['type'] = $val['type'];
        }
        $joinNum = $this->redis->ssize(REDIS_PREFIX."GAJoin_".$gid."_".$aid);
        $comment = $this->load('groupActivity')->getCommend($aid);
        $commentList = array();
        foreach($comment as $k=>$data){
            $user = $this->load('client')->getUserInfo($data['uid']);
            $commentList[$k]['cid'] = $data['cid'];
            $commentList[$k]['uid'] = $data['uid'];
            $commentList[$k]['content'] = $data['content'];
            $commentList[$k]['add_time'] = $data['add_time'];
            $commentList[$k]['name'] = $user['nickname'];
            $commentList[$k]['header'] = $user['header'];
        }
        $data = array(
            "role"=>$role,
            'title' => $info['title'],
            "aid" => $info['aid'],
            "gid"=> $info['gid'],
            "uid"=> $info['uid'],
            "type"=> intval($info['type']),
            'isJoin' => $this->load('groupActivity')->isJoin($aid,$uid,$gid),
            'place'=> $info['place'],
            "stime"=>$info['stime'],
            "etime"=>$info['etime'],
            "img"=>$info['img'],
            "cost"=>$info['cost'],
            "introduce"=>$info['introduce'],
            "name"=>$nickName,
            'isClaim' => intval($this->redis->sismember(REDIS_PREFIX."ACTaccept_".$info['aid'],$gid)),
            "header"=>$header,
            "joins"=>$joins,
            "gName" => isset($groupInfo['name']) ? $groupInfo['name'] : '',
            "joinNum" => $joinNum,
            "days" => $info['days'],
            "way" => intval($info['way']),
            "isverify" => isset($groupInfo['isverify']) ? intval($groupInfo['isverify']) : 0,
            "target"=>$info['target'],
            'groupStatus'=>$this->load('group')->getGroupStatus($uid,$gid),
            'status'=>$info['status'],
            'url'=>$info['url'],
            "activity"=>$actList,
            "comment"=>$commentList,
            "isNotice"=> intval($this->redis->sismember(REDIS_PREFIX."GAJoin_".$gid."_".$aid,$uid))
        );
        $this->result = $data;
    }

    /**
     * 2.7.2活动统计
     */
    public function dostatist(){
        $uid = $this->uid;
        if(empty($uid)){
            $_ENV['error']->getErrors(201);
            exit;
        }
        $aid = common::request('aid','G','',true);
        $gid = common::request('gid','G','',true);
        $id = common::request('id','G',0,true);
        $limit = common::request('offset','G',10,true);
        if(empty($aid) || empty($gid)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $actInfo = $this->load('groupActivity')->getActByAid($aid);
        if(empty($actInfo)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $reData = $this->load('groupActivity')->actStatist($gid,$aid,$id,$limit);
        $this->result = $reData;
    }

    /**
     * 商品介绍页
     */
    public function dogoodsIntroduce(){
        $uid = $this->uid;
        if(empty($uid)){
            $_ENV['error']->getErrors(201);
            exit;
        }
        $goods_id = common::request('goods_id','G','',true);
        $goodsInfo = $this->load('goods')->getGoodsById($goods_id);
        $this->result['introduce'] = $goodsInfo['introduce'];

    }

    /**
     * 物流详情
     */
    public function dologisticDetail(){
        $shipping_num = common::request('shipping_num','G','',true);
        $shipping_code = common::request('shipping_code','G','',true);
        if(empty($this->uid)){
            $_ENV['error']->getErrors(201);
            exit;
        }
        if(empty($shipping_code) || empty($shipping_num)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $this->loadLib('kd');
        $kd = new Kd();
        $logisticInfo = $kd->getLogisticDetail($shipping_code,$shipping_num);
        $logisticInfo = json_decode($logisticInfo,true);
        $logistic['shipping_num'] = $shipping_num; //快递单号
        $logistic['shipping_name'] = $this->load('order')->getShippingName($shipping_code);
        if($logisticInfo['Success'] == 1){
            $logistic['traces'] = $logisticInfo['Traces'];
        }else{
            $logistic['traces'] = $logisticInfo['Reason'];
        }
        $this->result['logisticInfo'] = $logistic;
    }

    /**
     * 官方活动群组排行
     */
    public function dogroupRank(){
        $aid = common::request('aid','G');
        $gid = common::request('gid','G');
        $id = common::request('id','G',0);//分页群ID
        if(empty($aid) || empty($gid)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        //首次请求显示当前群组排行信息
        if($id <= 0){
            $groupInfo = $this->load('group')->getGroupInfo($gid);
            $curGroup = [];
            if($this->redis->sismember(REDIS_PREFIX."ACTaccept_".$aid,$gid)) {
                $curGroup = [
                    'gid' => $gid,
                    'name' => $groupInfo['name'],
                    'header' => $groupInfo['header'],
                    'rank' => intval($this->redis->zrevrank(REDIS_PREFIX . 'GroupAct_' . $aid, $gid)) + 1,
                    'mileage' => floatval($this->redis->zscore(REDIS_PREFIX . 'GroupAct_' . $aid, $gid))
                ];
            }
            $data['curGroup'] = $curGroup;
        }
        $list = $this->load('groupActivity')->groupRank($aid,$id);
        $data['list'] = $list;
        $data['type'] = intval($this->redis->hget(REDIS_PREFIX.'ActivityInfo_'.$aid,'type'));
        $this->result = $data;
    }

    /**
     * 2.7.2 活动详情
     */
    public function donewDetail(){
        parent::dodetail();
    }
    
    /**
     * 我有管理权限的群组
     * 从group.php 复制过来 ljj
     */
    public function domyManageGroup(){
        $uid = $this->uid;
        if(empty($uid))
        {
            $_ENV['error']->getErrors(201);
            exit;
        }
        $created = $this->load('group')->myGroupListByRole($uid, 1);
        $manager = $this->load('group')->myGroupListByRole($uid, 2);
        $groups = array_merge($created,$manager);
        $this->result['result'] = compact('groups');
    }

    public function __destruct(){
        if(!isset($this->result['status'])) $this->result['status'] = array('code' => 200, 'msg' => '正常');
        echo json_encode($this->result);
    }
}